import React, { Component } from 'react'
import { Card, Button, Table, Modal, message } from 'antd'
import { PlusOutlined, ExclamationCircleOutlined, LeftOutlined } from '@ant-design/icons'
import AddClass from '../../components/AddClass'
import http from "../../api"
import "./index.css"

const { confirm } = Modal

export default class CommodityClassification extends Component {
  state = { visible: false, parentId: 0, categoryArr: [], loading: true, record: {}, recordId: {}, modify: false }
  myRef = React.createRef()
  columns = [
    {
      title: '分类名称',
      dataIndex: 'name',
    },
    {
      title: '操作',
      align: 'center',
      width: '25%',
      render: () => (
        <>
          <Button type="ghost" size="small" onClick={ this.reviseCategory } style={{ margin: '0 5px', fontSize: '12px' }}>修改分类</Button>
          <Button type="ghost" size="small" onClick={ this.deleteCategory } style={{ margin: '0 5px', fontSize: '12px' }}>删除分类</Button>
          <Button type="ghost" size="small" onClick={ this.checkSubclass } style={{ margin: '0 5px', fontSize: '12px' }}>查看子分类</Button>
        </>
      )
    },
  ]
  // 添加分类按钮回调
  showModal = () => { 
    this.setState({ visible: true, modify: false })
  }
  // 修改分类按钮回调
  reviseCategory = () => {
    setTimeout(() => {
      this.setState({ visible: true, modify: true })
    })
  }
  // 查看子分类按钮回调
  checkSubclass = () => {
    setTimeout(async () => {
      const item = await http.post('/rest/category/subclass', this.state.record)
      item.data.forEach(elem => {
        elem.key = elem._id
      })
      let { categoryArr, parentId } = this.state
      parentId++
      this.setState({ parentId, categoryArr: [...categoryArr, item.data] })
    })
  }
  // 删除分类按钮回调
  deleteCategory = () => {
    setTimeout(() => {
      confirm({
        title: `确定要删除 "${this.state.record.name}" 分类吗?`,
        icon: <ExclamationCircleOutlined />,
        content: '删除后将不能恢复',
        okText: '确认',
        cancelText: '取消',
        // 确定按钮回调
        onOk: async () => {
          const { _id } = this.state.record
          const item = await http.delete('/rest/category/delete', {params: { _id }})
          this.callGetCategory()
          message.success(item.data.message)
        }
      })
    })
  }
  // 确定按钮回调, 添加或更新分类请求
  hideModal = async () => {
    // 获取新添加分类的信息
    const { name, parent, _id } = this.myRef.current.state
    if(!name) return message.warn('分类名称不能为空')
    this.setState({ visible: false })
    let item = {}
    if(_id) {
      // 更新
      item = await http.post('/rest/category/update', { name, parent, _id })
      this.callGetCategory()
    } else {
      // 添加
      item = await http.post('/rest/category', { name, parent })
      // 添加完后再次获取数据
      this.callGetCategory()
    }
    message.success(item.data.message)
  }
  // 取消按钮回调
  handleCancel = () => { this.setState({ visible: false }) }
  callGetCategory = () => {
    if(this.state.parentId === 0) {
      this.getCategory()
    } else {
      this.getTowCategory()
    }
  }
  // 异步获取分类数据
  getCategory = async () => {
    // 发送获取分类数据请求
    const item = await http.get('/rest/category')
    const levelData = []
    // 给每个分类添加 key , 并且分好一级分类和二级分类
    item.data.forEach(element => {
      element.key = element._id
      levelData.push(element)
    })
    this.setState({ categoryArr: [levelData], loading: false  })
  }
  getTowCategory = async() => {
    const item = await http.post('/rest/category/subclass', this.state.recordId)
    item.data.forEach(elem => {
      elem.key = elem._id
    })
    let { categoryArr, parentId } = this.state
    categoryArr.splice(parentId, 1, item.data)
    this.setState({ categoryArr: [...categoryArr] })
  }
  // 组件挂载完毕获取分类数据
  componentDidMount() {
    this.getCategory()
  }
  reduceId = () => {
    let { parentId, categoryArr } = this.state
    categoryArr.pop()
    this.setState({ parentId: --parentId, categoryArr: [...categoryArr] })
  }
  render() {
    const { categoryArr, parentId, record, modify, recordId } = this.state
    // 表格要渲染的数据
    const dataSource = categoryArr[parentId]
    // 分页器所需的数据长度
    const total = dataSource ? dataSource.length : 0
    const extra = (
      <>
        {
          this.state.parentId > 0 ? 
          <Button icon={<LeftOutlined />} onClick={ this.reduceId } style={{ marginRight: '100px' }}>上级分类</Button> : ''
        }
        <Button type="primary" icon={<PlusOutlined />} onClick={this.showModal}>添加</Button>
      </>
    )
    return (
      <div className="commodity">
        <Card
          title={ parentId ? recordId.name : '一级分类列表' }
          headStyle={{ fontWeight: '700', color: '#1DA57A' }}
          extra={extra}
          style={{ height: '100%' }}
        >
          <Table
            dataSource={dataSource}
            columns={this.columns}
            bordered={true}
            loading={this.state.loading}
            pagination={{
              defaultCurrent: 1,
              total: total,
              pageSize: 5,
              responsive: true,
              showSizeChanger: false,
              showQuickJumper: true,
              position: ['bottomCenter']
            }}
            onRow={ record  => {
              return {
                // 鼠标点击行
                onClick: () => { 
                  const { _id } = this.state.recordId
                  if(record.parent !== _id) {
                    const recordId  = record
                    this.setState({ record, recordId }) 
                  } else {
                    (this.state.parentId === 0) && this.setState({ recordId: record })
                    this.setState({ record }) 
                  }
                }
              }
            } }
          />
        </Card>
        {
          // visible 为 true 时再加载组件 <Modal />,这样就可以清除Modal的数据，也可以获取到最新的数据
          this.state.visible &&
          <Modal
            title={ modify ? '修改分类' : '添加分类' }
            visible={this.state.visible}
            onOk={this.hideModal}
            onCancel={this.handleCancel}
            okText="确认"
            cancelText="取消"
          >
            <AddClass 
              ref={this.myRef}
              levelData={ parentId === 0 ? categoryArr[parentId] : categoryArr[parentId - 1] } 
              // 判断是否传递要修改分类的数据
              record={ modify ? record : ''} 
            />
          </Modal>
        }
      </div>
    )
  }
}
